package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.entity.User;
import server.demo.service.UserService;

import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, Object>>> login(
            @RequestBody Map<String, String> loginData,
            HttpSession session) {
        try {
            String username = loginData.get("username");
            String password = loginData.get("password");
            
            User user = userService.authenticateUser(username, password);
            if (user != null) {
                session.setAttribute("userId", user.getId());
                session.setAttribute("userRole", user.getRole().toString());
                
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("id", user.getId());
                responseData.put("username", user.getUsername());
                responseData.put("realName", user.getRealName());
                responseData.put("role", user.getRole().toString());
                responseData.put("email", user.getEmail());
                responseData.put("phone", user.getPhone());
                
                return ResponseEntity.ok(ApiResponse.success(responseData));
            } else {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("用户名或密码错误"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("登录失败：" + e.getMessage()));
        }
    }
    
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout(HttpSession session) {
        try {
            session.invalidate();
            return ResponseEntity.ok(ApiResponse.success("登出成功", null));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("登出失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/current")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCurrentUser(HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return ResponseEntity.status(401)
                    .body(ApiResponse.error("用户未登录"));
            }
            
            Optional<User> userOpt = userService.getUserById(userId);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("id", user.getId());
                responseData.put("username", user.getUsername());
                responseData.put("realName", user.getRealName());
                responseData.put("role", user.getRole().toString());
                responseData.put("email", user.getEmail());
                responseData.put("phone", user.getPhone());
                
                return ResponseEntity.ok(ApiResponse.success(responseData));
            } else {
                return ResponseEntity.status(401)
                    .body(ApiResponse.error("用户不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取用户信息失败：" + e.getMessage()));
        }
    }
    
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> register(@Valid @RequestBody User user) {
        try {
            // 验证必填字段
            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("用户名不能为空"));
            }
            if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("密码不能为空"));
            }
            if (user.getRealName() == null || user.getRealName().trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("真实姓名不能为空"));
            }
            
            // 验证密码长度
            if (user.getPassword().length() < 6) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("密码长度至少6位"));
            }
            
            // 检查用户名是否已存在
            Optional<User> existingUser = userService.getUserByUsername(user.getUsername());
            if (existingUser.isPresent()) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("用户名已存在"));
            }
            
            // 设置默认角色为普通用户
            user.setRole(User.UserRole.USER);
            user.setStatus(User.UserStatus.ACTIVE);
            
            User savedUser = userService.saveUser(user);
            savedUser.setPassword(null);
            return ResponseEntity.ok(ApiResponse.success("注册成功", savedUser));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("注册失败：" + e.getMessage()));
        }
    }
    
    @GetMapping
    public ResponseEntity<ApiResponse<List<User>>> getAllUsers(HttpSession session) {
        try {
            String userRole = (String) session.getAttribute("userRole");
            if (!"ADMIN".equals(userRole)) {
                return ResponseEntity.status(403)
                    .body(ApiResponse.error("权限不足"));
            }
            
            List<User> users = userService.getAllUsers();
            users.forEach(user -> user.setPassword(null));
            return ResponseEntity.ok(ApiResponse.success(users));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取用户列表失败：" + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable Long id, HttpSession session) {
        try {
            String userRole = (String) session.getAttribute("userRole");
            Long currentUserId = (Long) session.getAttribute("userId");
            
            if (!"ADMIN".equals(userRole)) {
                return ResponseEntity.status(403)
                    .body(ApiResponse.error("权限不足"));
            }
            
            // 不能删除自己
            if (id.equals(currentUserId)) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("不能删除自己的账号"));
            }
            
            // 检查用户是否存在
            Optional<User> userOpt = userService.getUserById(id);
            if (!userOpt.isPresent()) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("用户不存在"));
            }
            
            userService.deleteUser(id);
            return ResponseEntity.ok(ApiResponse.success("删除用户成功", null));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("删除用户失败：" + e.getMessage()));
        }
    }
}